﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace QueryData.LazyLoadWithoutProxy
{
    public class MainEntity
    {
        public MainEntity() { }

        public MainEntity(Action<object, string> lazyLoader) => _lazyLoader = lazyLoader;

        private Action<object, string> _lazyLoader;
        private List<SubEntity> _subEntities = new List<SubEntity>();

        public int Id { get; set; }
        public int Number { get; set; }

        public List<SubEntity> SubEntities
        {
            get => _lazyLoader.Load(this, ref _subEntities);
            set => _subEntities = value;
        }
    }

    public static class EfCoreLazyLoadingExtensions
    {
        public static TRelated Load<TRelated>(
            this Action<object, string> loader,
            object entity,
            ref TRelated navigationField,
            [CallerMemberName] string navigationName = null)
            where TRelated : class
        {
            loader?.Invoke(entity, navigationName);

            return navigationField;
        }
    }
}
